package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //用一个集合来封装begin 到 end的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);//添加开始时间
        //循环，日期加1，直到结束日期
        while (!begin.equals(end)){//判断开始时间是否等于结束时间
            //日期计算，begin加1天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //获取日期,封装成字符串
        String join = StringUtils.join(dateList, ",");

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        //得到具体的日期方便查询营业额
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null ? 0.0 : turnover;//营业额为null，则设置为0.0
        turnoverList.add(turnover);
        }
        String join1 = StringUtils.join(turnoverList, ",");
        return TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(join1)
                .build();
    }

    //用户统计
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //用一个集合来封装begin 到 end的日期
        List<LocalDate> dateList = new ArrayList<>();
        //添加开始时间
        dateList.add(begin);
        //循环，日期加1，直到结束日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //集合封装新用户
        //select count(id) from user where create_time > begin and create_time < end
        List<Integer> newUserList = new ArrayList<>();
        //集合封装总用户
        //select count(id) from user where create_time < end
        List<Integer> totalUserList = new ArrayList<>();
        //遍历日期集合
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
        //先查总用户，再查新用户，只写一条SQL语句
        Map map = new HashMap<>();
        map.put("end", endTime);
        Integer totalUser =  userMapper.getTotalUser(map);
        totalUserList.add(totalUser);
        map.put("begin", beginTime);
        Integer newUser = userMapper.getTotalUser(map);
        newUserList.add(newUser);

        }
        return UserReportVO.builder().dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //用一个集合来封装begin 到 end的日期
        List<LocalDate> dateList = new ArrayList<>();
        //添加开始时间
        dateList.add(begin);
        //循环，日期加1，直到结束日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List< Integer> orderCountList = new ArrayList<>();//存放每天的订单数
        List<Integer> validOrderCountList = new ArrayList<>();//存放每天的有效订单数
        //遍历这个日期集合
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单数 select count(id) from orders where order_time > begin and order_time < end
            Integer orderCount = countOrder(beginTime, endTime, null);

            //查询每天的完成订单数 select count(id) from orders where order_time > begin and order_time < end and status = 5
            Integer validOrderCount = countOrder(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

        }
        //计算订单数
        Integer orderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate =0.0;
        if (orderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / orderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    //销量统计
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {


            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
            List<GoodsSalesDTO> list = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> name = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> number = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameList = StringUtils.join(name, ",");
        String numberList = StringUtils.join(number, ",");


        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //1查询数据库，获取营业数据--查询最近三十天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVo =workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过poi将数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = null;
        try {
            //基于模板文件创建一个新的excel文件
            excel = new XSSFWorkbook(in);
            //获取表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+
                    dateBegin + "至" + dateEnd);
            //获取第四行
            XSSFRow row = sheet.getRow(3);//获取第四行
            //填充数据--营业额
            row.getCell(2).setCellValue(businessDataVo.getTurnover());
            //
            row.getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
            //
            row.getCell(6).setCellValue(businessDataVo.getNewUsers());

            //获取第五行
            row = sheet.getRow(4);
            //填充数据--有效订单数
            row.getCell(2).setCellValue(businessDataVo.getValidOrderCount());

            row.getCell(4).setCellValue(businessDataVo.getUnitPrice());//

            //填充数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
               BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            //获取某一行
            XSSFRow dataRow = sheet.getRow(7 + i);
            dataRow.getCell(1).setCellValue(date.toString());
            dataRow.getCell(2).setCellValue(businessData.getTurnover());
            dataRow.getCell(3).setCellValue(businessData.getValidOrderCount());
            dataRow.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            dataRow.getCell(5).setCellValue(businessData.getUnitPrice());
            dataRow.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            in.close();
            excel.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private Integer countOrder(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.getCountByMap(map);
    }
}
